<script setup>
    //粒子背景插件
    import { options } from './config/particles-config'
    //
    import { useRouter } from 'vue-router'
    import { ref } from 'vue';
    import { ElMessage } from 'element-plus'
    import { handleRegister as RegisterApi } from '../api/Register'

    const RegisterForm = ref({
        name: '',
        phone: '',
        password: '',
        sex: '', // 可选
        birthday: '', // 可选
        email: '', // 可选
    });

    const confirmPassword = ref('');

    // 定义 formRef 用于引用表单
    const formRef = ref(null);

    const validateConfirmPassword = (rule, value=confirmPassword.value, callback) => {
        if (value === '') {
            callback(new Error('请再次输入密码'));
        } else if (value !== RegisterForm.value.password) {
            callback(new Error('两次输入的密码不一致'));
        } else {
            callback();
        }
    };

    const rules = {
        name: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '用户名长度应在 3 到 10 个字符之间', trigger: ['blur', 'change'] }
        ],
        phone:[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { pattern: /\d{11}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min:6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'change' }
        ],
        confirmPassword: [
            { required: true, validator: validateConfirmPassword, trigger: ['blur', 'change'] },
        ],
        email: [
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
    }
    
    const router  = useRouter()

    const handleRegister = async () => {
        try {
            // 手动触发表单验证
            const form = RegisterForm.value;
            const valid = await formRef.value.validate();
            if (!valid) {
                ElMessage.error('请完善表单信息');
                return;
            }

            console.log('注册信息:', RegisterForm.value);
            //todo 这里可以添加注册逻辑
            const response = await RegisterApi(RegisterForm.value);
            console.log("response: ", response);
            if (response.data.code === 200) {
                ElMessage.success('注册成功!')
                setTimeout(() => {
                    // 检查用户是否仍然在当前页面
                    if (router.currentRoute.value.name === 'Register') {
                        router.push("/login")
                    }
                }, 3000);
            } else {
                ElMessage.error(response.data.data)
            }
        } catch (error) {
            console.log(error);
            ElMessage.error('注册失败!')
        }
    }

    const goToLogin = () => {
        router.push("/login")
    }
</script>

<template>

    <div class="register-container">
        <!-- 粒子背景插件 -->
        <Particles id="tsparticles" class="register-background" :options="options" />

        <el-card class="register-card">

            <h1 class="register-title">注册</h1>

            <div class="register-form">

                <el-form :model="RegisterForm" :rules="rules" ref="formRef" @submit.prevent="handleRegister">

                    <el-row>
                        <el-col :span="24">
                        <el-form-item label="用户名" label-width="80px" prop="name">
                            <el-input v-model="RegisterForm.name" autocomplete="off" prefix-icon="user" maxlength="10" show-word-limit placeholder="请输入用户名"/>
                        </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                        <el-form-item label="手机号" label-width="80px" prop="phone">
                            <el-input type="tel" v-model="RegisterForm.phone" autocomplete="off" prefix-icon="phone" placeholder="请输入手机号码"/>
                        </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                        <el-form-item label="密码" label-width="80px" prop="password">
                            <el-input type="password" v-model="RegisterForm.password" autocomplete="off" prefix-icon="lock" show-password placeholder="请输入密码"/>
                        </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                        <el-form-item label="确认密码" label-width="80px" prop="confirmPassword">
                            <el-input type="password" v-model="confirmPassword" autocomplete="off" prefix-icon="lock" show-password placeholder="请再次输入密码"/>
                        </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="邮箱" label-width="80px" prop="email">
                                <el-input v-model="RegisterForm.email" autocomplete="off" prefix-icon="message" placeholder="请输入邮箱"/>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="性别" label-width="80px" prop="sex">
                                <el-select v-model="RegisterForm.sex" placeholder="请选择性别">
                                    <el-option label="男" value="male"></el-option>
                                    <el-option label="女" value="female"></el-option>
                                    <el-option label="其他" value="other"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="出生日期" label-width="80px" prop="birthday">
                                <el-date-picker v-model="RegisterForm.birthday" type="date" placeholder="请选择出生日期"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-form-item style="width: 100%;">
                            <el-button type="primary" @click="handleRegister" style="width: 100%;">注册</el-button>
                        </el-form-item>
                    </el-row>

                    <el-row>
                        <el-form-item style="width: 100%;">
                            <el-button type="primary" @click="goToLogin" style="width: 100%;">登录</el-button>
                        </el-form-item>
                    </el-row>
                    
                </el-form>
                <RouterView />
            </div>

        
        </el-card>
    </div>

</template>

<style scoped>
    .register-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
    }
    
    .register-card {
        width: 500px;
        padding: 20px;
        background-color: #cde3fba3;
    }
    .register-title {
        text-align: center;
        margin-bottom: 20px;
        color: #105faf;
    }
    .register-form {
        width: 100%;
    }

    .register-background {
        height: 100%;
        width: 100%;
        background-size: cover;
        background-repeat: no-repeat;
        /*background-image: url('@/assets/bgImg/login-bg-1.webp');*/
        opacity:0.7;
        position:fixed;
        pointer-events: none;
    }

    .flex {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }
</style>